/**
 * 
 */
package soft.ay.qram;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import soft.ay.qram.helpers.FileWatchdog;

/**
 * @author vsuns
 *
 */
public class DataSource
{
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private HikariDataSource ds;
    private boolean ready = false;

    // ------------------分割线------------------
    // 静态子类
    private static class StaticSingleHolder
    {
        private static DataSource instance = null;
        private static FileWatchdog watchCacheFile = null;
        static
        {
            if (watchCacheFile == null)
            {
                watchCacheFile = new FileWatchdog();
                watchCacheFile.start();
            }
            instance = new DataSource();
            instance.resetDataSource();
        }
    }

    // 实例
    public static DataSource getInstance()
    {
        return StaticSingleHolder.instance;
    }

    // 私有构造
    private DataSource()
    {
    }

    // 获得数据库连接
    public Connection getConnection() throws SQLException
    {
        while (!ready)
        {
            logger.warn("waiting for ds ready");
        }
        return ds.getConnection();
    }

    // reset datasource
    public void resetDataSource(){
        this.ready = false;
        if (this.ds != null && !this.ds.isClosed())
        {
            ds.close();
        }
        // 数据库连接池
        Properties props = new Properties();
        props.setProperty("dataSourceClassName", "org.sqlite.SQLiteDataSource");
        props.setProperty("dataSource.url", "jdbc:sqlite:cache.db");
        props.setProperty("connectionTestQuery", "select 1");
        HikariConfig config = new HikariConfig(props);
        this.ds = new HikariDataSource(config);
        this.ready = true;
    }
}
